package com.cqs.learning.reflect;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.function.Predicate;

/**
 * 1. jdk proxy 的使用
 * 2. 理解为啥有接口的限制: 生成的代理类会继承Proxy根据java的单继承
 *
 * @author lixiaowen
 * @create 2020-01-04
 */
public class JdkProxyDemo {


    static class ProxyHandler implements InvocationHandler {

        private Object target;

        public ProxyHandler(Object target) {
            this.target = target;
        }


        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return method.invoke(target, args);
        }
    }

    public static void main(String[] args) throws IntrospectionException, InterruptedException {
        // 1.被代理的对象
        Predicate<Integer> predicate = integer -> integer > 100;
        //2.handler实现类
        ProxyHandler handler = new ProxyHandler(predicate);
        //3.新建Proxy对象
        Predicate<Integer> pre = (Predicate) Proxy.newProxyInstance(Predicate.class.getClassLoader(), new Class[]{Predicate.class}, handler);
        System.out.println(pre.getClass());//class com.sun.proxy.$Proxy0
        Thread.currentThread().join();
    }
}
